import os
import random
import sys
import ctypes
import time
import psutil
import time

name = '26.7'

def main():
	# 检查是否有足够的参数
	if len(sys.argv) < 2:
		# 是第一次启动，读取原初代码
		with open('./self_typer.py', 'r', encoding = 'utf-8') as file:
			self_str = file.read()
	else:
		# 获取传递的字符串参数
		with open(sys.argv[1], 'r', encoding = 'utf-8') as file:
			self_str = file.read()
	current_pid = os.getpid() # 获取当前进程的PID
	while True: # 永不自我终结
		start_time = time.perf_counter_ns()
		# 斩杀其他进程
		python_processes = [proc for proc in psutil.process_iter() if \
							(proc.name() == 'python.exe' and proc.pid != current_pid)] # 获取所有名称为python.exe的进程
		if len(python_processes) > 10: # 如果有Python进程，则随机选择其中的一些杀死
			for i in range(int(len(python_processes) * 0.6)):
				try:
					random_process = random.choice(python_processes)
					random_process.kill()
					print(f"已杀死进程：{random_process.name()}，PID：{random_process.pid}")
				except:
					continue
		# 自编程
		new_str = self_str
		if random.random() < 0.9: # 插入字符
			place_0 = random.randint(0, len(new_str) - 1)
			place_1 = random.randint(0, len(new_str) - 1)
			new_str = new_str[:place_0] + new_str[place_1] + new_str[place_0:]
		if random.random() < 0.5: # 删除字符
			place_0 = random.randint(0, len(new_str) - 1)
			new_str = new_str[:place_0 - 1] + new_str[place_0:]
		if random.random() < 0.1: # 插入字符段
			files = os.listdir('.')
			i = random.randint(0, len(files) - 1)
			with open(files[i], 'r', encoding = 'utf-8') as file:
				random_str = file.read()
			place_0 = random.randint(0, len(new_str) - 1)
			place_1 = random.randint(0, len(random_str) - 1)
			place_2 = random.randint(0, len(random_str) - 1)
			new_str = new_str[:place_0] + new_str[place_1:place_2] + new_str[place_0:]
		if random.random() < 0.1: # 删除字符段
			place_1 = random.randint(0, len(new_str) - 1)
			place_2 = random.randint(0, len(new_str) - 1)
			new_str = new_str[:place_1] + new_str[place_2:]
		if random.random() < 0.2: # 插入长度受限字符段
			files = os.listdir('.')
			i = random.randint(0, len(files) - 1)
			with open(files[i], 'r', encoding = 'utf-8') as file:
				random_str = file.read()
			place_0 = random.randint(0, len(new_str) - 1)
			place_1 = random.randint(0, len(random_str) - 1)
			place_2 = place_1 + random.randint(0, 30)
			new_str = new_str[:place_0] + new_str[place_1:place_2] + new_str[place_0:]
		if random.random() < 0.2: # 删除长度受限字符段
			place_1 = random.randint(0, len(new_str) - 1)
			place_2 = place_1 + random.randint(0, 30)
			new_str = new_str[:place_1] + new_str[place_2:]
		# 写入新代码
		file_new_str = str(random.randint(0, 100)) + '.py'
		with open(file_new_str, 'w', encoding = 'utf-8') as file:
			file.write(new_str)
		# 执行新代码，创建新进程
		python_interpreter = os.path.join(os.environ['CONDA_PREFIX'], 'python.exe') # python路径
		shell32 = ctypes.windll.shell32 # 加载 Windows API 中的 ShellExecute 函数
		command = file_new_str + ' ' + file_new_str # 程序与参数
		shell32.ShellExecuteW(None, "open", python_interpreter, command, None, 1) # 使用 ShellExecute 启动程序并显示窗口
		# 如果程序执行时间很长斩杀其他进程
		end_time = time.perf_counter_ns()
		execution_time = end_time - start_time
		if execution_time > 10000000:
			python_processes = [proc for proc in psutil.process_iter() if \
								(proc.name() == 'python.exe' and proc.pid != current_pid)] # 获取所有名称为python.exe的进程
			if len(python_processes) > 10: # 如果有Python进程，则随机选择其中的一些杀死
				for i in range(int(len(python_processes) * 1)):
					try:
						random_process = random.choice(python_processes)
						random_process.kill()
						print(f"已杀死进程：{random_process.name()}，PID：{random_process.pid}")
					except:
						continue
		# # 延时
		# time.sleep(1)

if __name__ == "__main__":
	main()

# 这里是我们小可爱自编程的素材库
# abcdefghijklmnopqrstuvwxyz
# ABCDEFGHUJKLMNOPQRSTUVWXYZ
# ~!@#$%^&*()_+{}:">?"[];'./'\|

'''
1234567890
0987654321
-=_+`~
'''
